<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button data-hash="eat">吃饭</button>
    <button data-hash="sleep">睡觉</button>
    <button data-hash="play">打豆豆</button>
    <div class="content"></div>
    <script>
      let btn = document.querySelectorAll('button')
      let content = document.querySelector('.content')

      let hashRoute = [
        { path: '/eat', content: '吃饭' },
        { path: '/sleep', content: '睡觉' },
        { path: '/play', content: '打豆豆' },
      ]
      btn.forEach((item) => {
        item.onclick = function () {
          location.hash = this.dataset.hash
        }
      })
      //   当页面哈希值修改时发生改动
      window.onhashchange = function (e) {
        let hash = e.newURL.split('#')[1]
        hashRoute.forEach((item) => {
          if (item.path === '/' + hash) {
            content.textContent = item.content
          }
        })
      }
    </script>
  </body>
</html>
